package com.xiaohei.process.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xiaohei.auth.service.SysUserService;
import com.xiaohei.model.process.Process;
import com.xiaohei.model.process.ProcessTemplate;
import com.xiaohei.model.system.SysUser;
import com.xiaohei.process.service.MessageService;
import com.xiaohei.process.service.ProcessService;
import com.xiaohei.process.service.ProcessTemplateService;
import com.xiaohei.security.custom.LoginUserInfoHelper;
import com.xiaohei.vo.process.ProcessFormVo;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassName: MessageServiceImpl
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/5/7 19:58
 * Version 1.0
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private ProcessService processService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ProcessTemplateService processTemplateService;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private MessageService messageService;

    /**
     * 推送待审批人员
     *
     * @param processId
     * @param userId
     * @param taskId
     */
    @Override
    public void pushPendingMessage(Long processId, Long userId, String taskId) {
        //查询流程信息
        Process process = processService.getById(processId);

        //根据userid查询要推送人的信息
        SysUser sysUser = sysUserService.getById(userId);

        //根据taskid
        ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());

        //得到提交人的信息
        SysUser submitSysUser = sysUserService.getById(process.getUserId());

        //获取要给的信息人的openId
        String openId = sysUser.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            //TODO: 为了测试  空就添加自己的openid值
            openId = "omwf25izKON9dktgoy0dogqvnGhk";
        }

        //设置消息发送的信息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)  //给哪个用户发信息   放openID值
                //模版信息的id值
                .templateId("uRUDMrFuuEX_Yk2rj6xY5reTELShANCEWamDroVj0Pk")
                //点击消息跳转的地址
                .url("http://39c794e6.r8.cpolar.top/#/show" + processId + "/" + taskId)
                .build();

        JSONObject jsonObject = JSON.parseObject(process.getFormValues());
        JSONObject formShowData = jsonObject.getJSONObject("formShowData");
        StringBuffer content = new StringBuffer();
        for (Map.Entry entry : formShowData.entrySet()) {
            content.append(entry.getKey()).append("：").append(entry.getValue()).append("\n ");
        }

        //设置模版里参数值
        templateMessage.addData(new WxMpTemplateData("first",
                submitSysUser.getName() + "提交了申请" + processTemplate.getName() + ",请注意查看", "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword1", process.getProcessCode(), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword2", new DateTime(process.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"), "#272727"));
        templateMessage.addData(new WxMpTemplateData("content", content.toString(), "#272727"));

        //调用方法
        String msg = null;
        try {
            msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 审批后推送提交审批人员
     *
     * @param processId
     * @param userId
     * @param status
     */
    @Override
    public void pushProcessedMessage(Long processId, Long userId, Integer status) {
        Process process = processService.getById(processId);
        ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());
        SysUser sysUser = sysUserService.getById(userId);
        SysUser currentSysUser = sysUserService.getById(LoginUserInfoHelper.getUserId());
        String openid = sysUser.getOpenId();
        if (StringUtils.isEmpty(openid)) {
            openid = "omwf25izKON9dktgoy0dogqvnGhk";
        }
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openid)//要推送的用户openid
                .templateId("uRUDMrFuuEX_Yk2rj6xY5reTELShANCEWamDroVj0Pk")//模板id
                .url("http://39c794e6.r8.cpolar.top/#/show" + processId + "/" + "/0")//点击模板消息要访问的网址
                .build();
        JSONObject jsonObject = JSON.parseObject(process.getFormValues());
        JSONObject formShowData = jsonObject.getJSONObject("formShowData");
        StringBuffer content = new StringBuffer();
        for (Map.Entry entry : formShowData.entrySet()) {
            content.append(entry.getKey()).append("：").append(entry.getValue()).append("\n ");
        }
        templateMessage.addData(new WxMpTemplateData("first", "你发起的" + processTemplate.getName() + "审批申请已经被处理了，请注意查看。", "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword1", process.getProcessCode(), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword2", new DateTime(process.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword3", currentSysUser.getName(), "#272727"));
        templateMessage.addData(new WxMpTemplateData("keyword4", status == 1 ? "审批通过" : "审批拒绝", status == 1 ? "#009966" : "#FF0033"));
        templateMessage.addData(new WxMpTemplateData("content", content.toString(), "#272727"));
        try {
            String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

}
